//
//  DeviceInfoCollector.m
//  Peso Guide
//
//  Created by macbook on 2025/6/20.
//

#import "DeviceInfoCollector.h"
#import <sys/utsname.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <AdSupport/AdSupport.h>
#import <UIKit/UIKit.h>
#import "AFNetworking.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <mach/mach_host.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
#import <sys/mount.h>

@implementation DeviceInfoCollector

+ (NSDictionary *)collectDeviceInfo {
    NSDictionary *dataDic = @{
        @"frame": [self getStorageInfo],
        @"powershell": [self getBatteryInfo],
        @"latex": [self getDeviceInfo],
        @"choose": [self getSecurityInfo],
        @"mechanism": [self getEnvironmentInfo],
        @"careful": [self getWifiInfo]
    };
    return dataDic;
}

// 存储和内存信息
+ (NSDictionary *)getStorageInfo {
//    NSString *availableStorage = [self getCanUseSize]; // 默认返回0避免审核问题
//    NSString *totalStorage = [self totalDiskSpace] ?: @0;
//    NSString *totalMemory = [self physicalMemory] ?: @0;
//    NSString *freeMemory = [self freeMemory] ?: @0;
    
    return @{
        @"activation": [self getCanUseSize],
        @"traverse": [self getTotalDiskSize],
        @"easy": [self getTotalStorageSizeOfTheDevice],
        @"fairly": [self getAvailableMemorySize]
    };
}

// 获取当前可用内存
+ (NSString *)getAvailableMemorySize {
    vm_statistics_data_t stats;
    mach_msg_type_number_t info = HOST_VM_INFO_COUNT;
    kern_return_t kern = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&stats, &info);
    if (kern != KERN_SUCCESS) {
        return @"内存查找失败";
    }
    long long canUseSize = ((vm_page_size * stats.free_count + vm_page_size * stats.inactive_count));
    return [self allSize:canUseSize];
}

//总存储大小
+ (NSString *)getTotalStorageSizeOfTheDevice{
    long long totalStorageSize = [NSProcessInfo processInfo].physicalMemory;
    return [self allSize:totalStorageSize];
}

// 获取总磁盘容量
+ (NSString *)getTotalDiskSize {
    struct statfs debf;
    unsigned long long allSize = -1;
    if (statfs("/var", &debf) >= 0) {
        allSize = (unsigned long long)(debf.f_bsize * debf.f_blocks);
    }
    return [self allSize:allSize];
}

// 获取可用磁盘容量
+ (NSString *)getCanUseSize {

    NSError *errorr = nil;
        NSDictionary *resultsDic = [[[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()] resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:&errorr];
        if(errorr){return @"-1";}
    
        return [NSString stringWithFormat:@"%@",resultsDic[NSURLVolumeAvailableCapacityForImportantUsageKey]];
}

+ (NSString *)allSize:(unsigned long long)size {
    NSInteger KB = 1024;
    NSInteger MB = KB*KB;
    NSInteger GB = MB*KB;
    
    return [NSString stringWithFormat:@"%llu",(size)];
}

+ (NSNumber *)totalDiskSpace {
    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    return attrs[NSFileSystemSize];
}

+ (NSNumber *)physicalMemory {
    return @(NSProcessInfo.processInfo.physicalMemory);
}

+ (NSNumber *)freeMemory {
    vm_statistics64_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    if (host_statistics64(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount) == KERN_SUCCESS) {
        return @(vm_page_size * vmStats.free_count);
    }
    return @0;
}

// 电池信息
+ (NSDictionary *)getBatteryInfo {
    UIDevice.currentDevice.batteryMonitoringEnabled = YES;
    float batteryLevel = UIDevice.currentDevice.batteryLevel;
    BOOL isCharging = UIDevice.currentDevice.batteryState == UIDeviceBatteryStateCharging ||
                     UIDevice.currentDevice.batteryState == UIDeviceBatteryStateFull;
    
    return @{
        @"dash": @((int)(batteryLevel * 100)),
        @"shell": isCharging ? @1 : @0
    };
}

// 设备基本信息
+ (NSDictionary *)getDeviceInfo {
    return @{
        @"emacs": UIDevice.currentDevice.systemVersion,
        @"logo": UIDevice.currentDevice.model,
        @"redefining": [self deviceModel]
    };
}

+ (NSString *)deviceModel {
    struct utsname systemInfo;
    uname(&systemInfo);
    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}

// 安全信息
+ (NSDictionary *)getSecurityInfo {
    return @{
        @"interference": [self isSimulator] ? @1 : @0,
        @"detect": [self isJailbroken] ? @1 : @0
    };
}

+ (BOOL)isSimulator {
#if TARGET_OS_SIMULATOR
    return YES;
#else
    return NO;
#endif
}

+ (BOOL)isJailbroken {
    // 简单越狱检测（避免触发苹果审核敏感行为）
    NSArray *paths = @[@"/Applications/Cydia.app"];
    for (NSString *path in paths) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            return YES;
        }
    }
    return NO;
}

// 环境信息
+ (NSDictionary *)getEnvironmentInfo {
    return @{
        @"assumptions": [self timezoneID],
        @"associates": [AppTools getOrCreatePseudoIDFV],
        @"incorrect": [NSLocale preferredLanguages].firstObject ?: @"",
        @"avoidance": [self networkType],
        @"table": [self advertisingIdentifier]
    };
}

+ (NSString *)timezoneID {
    return [NSTimeZone systemTimeZone].name;
}

+ (NSString *)networkType {
    AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWiFi:
            return @"WIFI";
        case AFNetworkReachabilityStatusReachableViaWWAN: {
            // 使用CoreTelephony判断具体网络类型
            CTTelephonyNetworkInfo *netinfo = [CTTelephonyNetworkInfo new];
            if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS] ||
                [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge]) {
                return @"2G";
            }
            // 其他3G/4G/5G判断...
            return @"4G"; // 简化处理
        }
        default:
            return @"OTHER";
    }
}

+ (NSString *)advertisingIdentifier {
    // 检查是否允许广告追踪
    return [AppTools getIDFA];
}

// WiFi信息
+ (NSDictionary *)getWifiInfo {
    NSDictionary *wifiDict = [self fetchCurrentWifiInfo];
    return @{
        @"benefit": @{
            @"policy": wifiDict[@"mac"] ?: @"",
            @"restriction": wifiDict[@"ssid"] ?: @""
        }
    };
}

+ (NSDictionary *)fetchCurrentWifiInfo {
#if TARGET_OS_SIMULATOR
    return @{}; // 模拟器无法获取
#else
    NSArray *interfaces = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *interface in interfaces) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)interface);
        if (info[@"SSID"]) {
            return @{
                @"ssid": info[@"SSID"],
                @"mac": [self getWiFiMACAddress] // iOS 13+ 已无法获取真实MAC地址
            };
        }
    }
    return @{};
#endif
}

+ (NSString *)getWiFiMACAddress {
    NSString *macAddress = nil;
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();

    if (!wifiInterfaces) {
        return nil;
    }

    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef wifiInfo = CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName);

        if (wifiInfo) {
            NSDictionary *info = (__bridge NSDictionary *)wifiInfo;
            macAddress = [info objectForKey:(__bridge NSString *)kCNNetworkInfoKeyBSSID];
            CFRelease(wifiInfo);
             if (macAddress) {
                break;
            }
        }
    }
    CFRelease(wifiInterfaces);
    return macAddress;
}

//获取设备IP地址
+(NSString *)getDeviceIP {
    int sockfd = socket(AF_INET,SOCK_DGRAM, 0);
    // if (sockfd <</span> 0) return nil;

    NSMutableArray *ips = [NSMutableArray array];

    int BUFFERSIZE =4096;
    struct ifconf ifc;
    char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
    struct ifreq *ifr, ifrcopy;
    
    ifc.ifc_len = BUFFERSIZE;
    ifc.ifc_buf = buffer;
    
    if (ioctl(sockfd,SIOCGIFCONF, &ifc) >= 0){
        
        for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
            
            ifr = (struct ifreq *)ptr;
            int len =sizeof(struct sockaddr);
            
            if (ifr->ifr_addr.sa_len > len) {
                len = ifr->ifr_addr.sa_len;
            }
            
            ptr += sizeof(ifr->ifr_name) + len;
            
            if (ifr->ifr_addr.sa_family !=AF_INET) continue;
            
            if ((cptr = (char *)strchr(ifr->ifr_name,':')) != NULL) *cptr =0;
            
            if (strncmp(lastname, ifr->ifr_name,IFNAMSIZ) == 0)continue;
            
            memcpy(lastname, ifr->ifr_name,IFNAMSIZ);
            
            ifrcopy = *ifr;
            
            ioctl(sockfd,SIOCGIFFLAGS, &ifrcopy);
            
            if ((ifrcopy.ifr_flags &IFF_UP) == 0)continue;
 
            NSString *ip = [NSString stringWithFormat:@"%s",inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
            [ips addObject:ip];
        }
    }
    close(sockfd);
 
    NSString *deviceIP =@"";
    
    for (int i=0; i < ips.count; i++){
        if (ips.count >0){
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
        }
    }
    
    return deviceIP;
}

@end
